package com.falcon.generator.java;

import com.falcon.config.GeneratorConfig;
import com.falcon.mapper.IColumnMapper;
import com.falcon.mapper.ITableMapper;
import com.falcon.constants.FtlConstant;
import com.falcon.domain.po.ColumnPO;
import com.falcon.domain.po.TablePO;
import com.falcon.utils.PathUtil;
import com.swan.core.utils.DateUtil;
import com.swan.core.utils.TxtFileUtil;
import com.swan.mybatis.condition.Condition;
import com.swan.mybatis.condition.OpType;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Slf4j
@Service
public abstract class JavaClassGenerator extends JavaAbsGenerator {

    protected abstract GeneratorConfig.ClassConfig getClassConfig();

    protected abstract String getTemplate();

    @Autowired
    private ITableMapper genTableMapper;

    @Autowired
    private IColumnMapper columnMapper;

    @Override
    public void generateCode(Long tableId) {

        TablePO tablePO = this.genTableMapper.selectById(tableId);

        Condition condition = Condition.newInstance().and(ColumnPO.Fields.tableId, OpType.equals, tablePO.getId());
        List<ColumnPO> ColumnPOs = this.columnMapper.selectList(condition);

        // 1.配置信息
        GeneratorConfig.ClassConfig classConfig = getClassConfig();

        String module = "";
        String packageName = config.getPackageName() + "." + module + "." + classConfig.getPackageName();
        if (getTemplate().equals(FtlConstant.FTL_CONTROLLER)) {
            module = "." + tablePO.getModuleName().split("-")[1];
            // controller 包结构为  controller.user、controller.file
            packageName = config.getPackageName()  + "." + classConfig.getPackageName() + "." + module;
        }

        // 根据模板生成代码
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("module", module);
        dataMap.put("table", tablePO);
        dataMap.put("columns", ColumnPOs);
        dataMap.put("config", config);
        dataMap.put("author", config.getAuthor());
        dataMap.put("createDate", DateUtil.getToday());

        // 生成代码
        String code = freemarkerTemplateInside.getContent(getTemplate(), dataMap);

        // 文件路径
        String fileName = getName(classConfig.getNamePrefix(), tablePO.getClassName(), classConfig.getNameSuffix());
        String modulePath = this.geGenerateCodePath() + "/" + tablePO.getModuleName();

        String filePath = PathUtil.getClassPath(modulePath, packageName, fileName);

        // 写入文件
        TxtFileUtil.writeFile(filePath, true, code);
    }
}
